package com.wyl.salary.ui.viewmodel

import android.app.Application
import android.content.Context
import android.content.Intent
import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.core.content.ContextCompat
import androidx.lifecycle.AndroidViewModel
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.wyl.salary.pojo.SalaryBean
import com.wyl.salary.pojo.SalaryBean_
import com.wyl.salary.repository.ObjectBox
import com.wyl.salary.utils.toDate

private const val TAG = "SalaryViewModel"

class SalaryViewModel(app: Application) : AndroidViewModel(app) {
    private val sp = app.getSharedPreferences("duration", 0)

    var salaries by mutableStateOf(listOf<SalaryBean>())

    /**
     * 上班总收入
     */
    var salary by mutableStateOf(0.0)
    var duration by mutableStateOf(0.0)

    /**
     * 外卖总收入
     */
    var tipping by mutableStateOf(0.0)

    init {
        getAllSalary()
    }

    fun getAllSalary() {
        val startDate = sp.getString("startDate", "")!!
        val endDate = sp.getString("endDate", "")!!
        salaries = ObjectBox.salaryBox.query()
            .apply {
                if (startDate.isNotEmpty() && endDate.isNotEmpty()) {
                    between(SalaryBean_.date, startDate.toDate(), endDate.toDate())
                }
            }
            .orderDesc(SalaryBean_.date)
            .build()
            .find()
        Log.d(TAG, "getAllSalary: $salaries")
        salary = salaries.sumOf { it.hours * it.salary }
        duration = salaries.sumOf { it.hours }
        tipping = salaries.sumOf { it.tipping }
    }

    fun exportData(context: Context) {
        val gson = Gson()
        val startDate = sp.getString("startDate", "")!!
        val endDate = sp.getString("endDate", "")!!
        // 定义一个 Intent 对象
        val sendingIntent = Intent().apply {
            action = Intent.ACTION_SEND  // 设置动作
            type = "text/json" // 设置内容类型
            putExtra(Intent.EXTRA_TEXT, gson.toJson(salaries)) // 添加内容
        }

        // 使用 Intent.createChooser() 获取 Intent 的一个版本
        val intent =
            Intent.createChooser(sendingIntent, "$startDate - $endDate")
        // 打开 ShareSheet 页面
        ContextCompat.startActivity(context, intent, null)
    }

    fun importData(json: String) {
        val gson = Gson()
//        Log.d(TAG, "importData: json = $json")
        val list =
            gson.fromJson<List<SalaryBean>>(json, object : TypeToken<List<SalaryBean>>() {}.type)
        if (list.isNotEmpty()) {
//            list.forEach { Log.d(TAG, "importData: bean = $it") }
            ObjectBox.salaryBox.put(list)
            getAllSalary()
        }
    }
}